package org.rainbowinverted.charging.device.connect.ykc.server.handler;

import org.rainbowinverted.charging.device.connect.ykc.server.message.in.YkcDeviceHeartbeatIn;
import org.rainbowinverted.charging.device.connect.ykc.server.message.in.YkcMessageIn;
import org.rainbowinverted.charging.device.connect.ykc.server.message.out.YkcDeviceHeartbeatOut;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 心跳处理器
 * @author hehuaiping
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class YkcDeviceHeartbeatHandler extends YkcAbstractHandler<YkcDeviceHeartbeatIn, YkcDeviceHeartbeatOut> {
    @Override
    public void read(ChannelHandlerContext channel, YkcMessageIn message) {
        ByteBuf messageBody = message.getMessageBody();
        Long deviceNo = readDeviceNo(messageBody);
        Integer gunNo = readGunNo(messageBody);
        // 0x00：正常 0x01：故障
        Boolean gunNormal = messageBody.readByte() == 0x00;
        YkcDeviceHeartbeatIn ykcDeviceHeartbeatIn = new YkcDeviceHeartbeatIn(deviceNo, gunNo, gunNormal);
        log.info("device heartbeat info :{}", ykcDeviceHeartbeatIn);
        channel.writeAndFlush(YkcDeviceHeartbeatOut.builder(message.getFrameSerialNo(), deviceNo, gunNo));
    }

    @Override
    public void write(ByteBuf byteBuf, YkcDeviceHeartbeatOut ykcDeviceHeartbeatOut) {
        writeDeviceNo(byteBuf, ykcDeviceHeartbeatOut.getDeviceNo());
        // 抢号
        byteBuf.writeByte(ykcDeviceHeartbeatOut.getGunNo().byteValue());
        // 心跳应答
        byteBuf.writeByte(ykcDeviceHeartbeatOut.getAck());
    }

    public Boolean getOnlineStatus(Long deviceNo) {
        return Objects.nonNull(getChannel(deviceNo));
    }
}
